<template>
    <div class="page-container" v-loading="loading">
        <el-page-header @back="goBack" :content="'订单详情: ' + (order.id || '')"></el-page-header>

        <el-card class="mt-4">
            <template #header>
                <div class="card-header">
                    <span>订单基本信息</span>
                    <el-tag :type="getStatusTag(order.status)">{{ getStatusText(order.status) }}</el-tag>
                </div>
            </template>
            <el-descriptions :column="2" border>
                <el-descriptions-item label="订单ID">{{ order.id }}</el-descriptions-item>
                <el-descriptions-item label="交易类型">{{ order.type }}</el-descriptions-item>
                <el-descriptions-item label="用户ID">{{ order.userId }}</el-descriptions-item>
                <el-descriptions-item label="账户ID">{{ order.accountId }}</el-descriptions-item>
                <el-descriptions-item label="交易总额">{{ order.amount?.toFixed(2) }}</el-descriptions-item>
                <el-descriptions-item label="审批人ID">{{ order.approverId || 'N/A' }}</el-descriptions-item>
                <el-descriptions-item label="创建时间">{{ new Date(order.createTime).toLocaleString()
                    }}</el-descriptions-item>
                <el-descriptions-item label="拒绝原因" v-if="order.status === 'REJECTED'">{{ order.rejectionReason || '无'
                    }}</el-descriptions-item>
            </el-descriptions>
        </el-card>

        <el-card class="mt-4">
            <template #header>订单明细</template>
            <el-table :data="order.details" style="width: 100%" border>
                <el-table-column prop="id" label="明细ID"></el-table-column>
                <el-table-column prop="fundCode" label="基金代码"></el-table-column>
                <el-table-column prop="direction" label="买卖方向">
                    <template #default="scope">
                        <el-tag :type="scope.row.direction === 'BUY' ? 'danger' : 'success'">
                            {{ scope.row.direction }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="amount" label="金额">
                    <template #default="scope">{{ scope.row.amount.toFixed(2) }}</template>
                </el-table-column>
                <el-table-column prop="status" label="状态">
                    <template #default="scope">
                        <el-tag :type="getStatusTag(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120">
                    <template #default="scope">
                        <el-button v-if="scope.row.status === 'FAILED'" size="small" type="warning"
                            @click="correctDetail(scope.row)">
                            修正
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <el-card class="mt-4" v-if="settlements.length > 0">
            <template #header>交割信息</template>
            <el-table :data="settlements" style="width: 100%" border>
                <el-table-column prop="orderDetailId" label="订单明细ID"></el-table-column>
                <el-table-column prop="settledAmount" label="成交金额">
                    <template #default="scope">{{ scope.row.settledAmount.toFixed(2) }}</template>
                </el-table-column>
                <el-table-column prop="settledShares" label="成交份额">
                    <template #default="scope">{{ scope.row.settledShares.toFixed(4) }}</template>
                </el-table-column>
                <el-table-column prop="fee" label="手续费">
                    <template #default="scope">{{ scope.row.fee.toFixed(2) }}</template>
                </el-table-column>
                <el-table-column prop="success" label="是否成功">
                    <template #default="scope">
                        <el-tag :type="scope.row.success ? 'success' : 'danger'">
                            {{ scope.row.success ? '是' : '否' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="failureReason" label="失败原因"></el-table-column>
            </el-table>
        </el-card>

    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import axios from 'axios';

const route = useRoute();
const router = useRouter();

const order = ref({});
const settlements = ref([]);
const loading = ref(true);

// 模拟从 tradeApi 导入函数
const tradeApi = {
    getTradeOrderDetails: (id) => axios.get(`/api/trade/order/${id}`),
    getSettlementsByOrderId: (id) => axios.get(`/api/settlements?orderId=${id}`),
};

const statusMap = {
    PENDING: { text: '待审批', type: 'warning' },
    APPROVED: { text: '已批准', type: '' },
    COMPLETED: { text: '已完成', type: 'success' },
    SETTLED: { text: '已结算', type: 'success' },
    PARTIALLY_SETTLED: { text: '部分结算', type: 'primary' },
    FAILED: { text: '失败', type: 'danger' },
    REJECTED: { text: '已拒绝', type: 'info' },
};

const getStatusText = (status) => statusMap[status]?.text || '未知';
const getStatusTag = (status) => statusMap[status]?.type || 'info';

const goBack = () => {
    router.back();
};

const correctDetail = (detail) => {
    router.push({
        name: 'TradeCorrection',
        params: {
            orderId: order.value.id,
            detailId: detail.id
        }
    });
};

onMounted(async () => {
    const orderId = route.params.id;
    if (orderId) {
        try {
            const [orderRes, settlementsRes] = await Promise.all([
                tradeApi.getTradeOrderDetails(orderId),
                tradeApi.getSettlementsByOrderId(orderId)
            ]);
            order.value = orderRes.data;
            settlements.value = settlementsRes.data;
        } catch (error) {
            ElMessage.error('获取订单详情失败: ' + (error.response?.data?.message || error.message));
        } finally {
            loading.value = false;
        }
    }
});
</script>

<style scoped>
.page-container {
    padding: 20px;
}

.mt-4 {
    margin-top: 1.5rem;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>